package common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

import tool.conn;

public class messageReceive {
	static conn conn;

	public messageReceive(){
		conn = new conn();
	}

	public int newRecord(String sql, Long time)
			throws ClassNotFoundException, SQLException {
		//SET IDENTITY_INSERT dbo.messagereceive OFF;
		//SET IDENTITY_INSERT dbo.messagereceive ON
		
		PreparedStatement pstmt = conn.PSexecuteUpdate("insert into messagereceive(sql,receiveTime,isDone)values(?,?,0);");
		pstmt.setString(1, sql);
		pstmt.setLong(2, time);
		return pstmt.executeUpdate();
	}

	public String viewAll() throws ClassNotFoundException, SQLException {
		StringBuffer sb = new StringBuffer();
		PreparedStatement pstmt = conn
				.PSexecuteUpdate("select * from messagereceive where isDone = '0' order by receiveTime asc");
		ResultSet rs = pstmt.executeQuery();
		while (rs.next()) {
			sb.append(rs.getString("sql") + "<br/>");
		}
		return sb.toString();
	}

	public boolean doRebuild(int id) throws SQLException {
		System.out.println(id);
		PreparedStatement pstmt = conn
				.PSexecuteUpdate("select * from messagereceive where id = "
						+ id);
		ResultSet rs = pstmt.executeQuery();
		while (rs.next()) {
			PreparedStatement pstmtrun = conn.PSexecuteUpdate(rs
					.getString("sql"));
			pstmtrun.execute();
			System.out.println("update");
			PreparedStatement pstmtedit = conn
					.PSexecuteUpdate("update messagereceive set isDone = 1 where id = "
							+ id);
			pstmtedit.execute();

		}
		return false;
	}

	public boolean doAllRebuild() throws SQLException {
		PreparedStatement pstmt = conn
				.PSexecuteUpdate("select * from messagereceive where isDone = '0' order by receiveTime asc");
		ResultSet rs = pstmt.executeQuery();
		while (rs.next()) {
			// System.out.println(rs.getInt("id"));
			doRebuild(rs.getInt("id"));
		}
		return true;
	}

}
